package services

import (
	"errors"
	"govue3/db"
	"govue3/models"
	"govue3/utils"

	"gorm.io/gorm"
)

type AuthService interface {
	Login(username, password string) (string, *models.User, error)
	Register(username, password string) error
}

type authService struct {
	sharding *db.Sharding
	cache    *utils.Cache
}

// 修改构造函数，注入分片和缓存依赖
func NewAuthService(sharding *db.Sharding, cache *utils.Cache) AuthService {
	return &authService{
		sharding: sharding,
		cache:    cache,
	}
}

func (s *authService) Login(username, password string) (string, *models.User, error) {
	// 使用分片数据库查询用户
	db := s.sharding.GetDB(username) // 根据用户名分片
	var user models.User
	if err := db.Where("username = ?", username).First(&user).Error; err != nil {
		return "", nil, errors.New("账号错误")
	}

	// 使用 bcrypt 验证密码
	if password != user.Password {
		return "", nil, errors.New("密码错误!")
	}

	token, err := utils.GenerateToken(user.ID)
	if err != nil {
		return "", nil, err
	}
	return token, &user, nil
}

func validateUser(username, password string) error {
	if username == "" {
		return errors.New("用户名不能为空")
	}
	if password == "" || len(password) < 6 {
		return errors.New("密码不能为空且长度必须大于等于6")
	}
	return nil
}

func (s *authService) Register(username, password string) error {
	if err := validateUser(username, password); err != nil {
		return err
	}

	// 分片选择数据库
	db := s.sharding.GetDB(username)
	if err := db.Where("username = ?", username).First(&models.User{}).Error; err == nil {
		return errors.New("用户名已存在")
	} else if !errors.Is(err, gorm.ErrRecordNotFound) {
		return err
	}

	user := &models.User{
		Username: username,
		Password: password,
	}

	if err := db.Create(user).Error; err != nil {
		return err
	}
	return nil
}
